import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import Home from '@/views/Home.vue'
import Auth from '@/views/Auth.vue'
import History from '@/views/History.vue'
import Game from '@/views/Game.vue'
import RoomLobby from '@/views/RoomLobby.vue'
// 测试页面路由移除

const routes = [
  {
    path: '/',
    name: 'Auth',
    component: Auth
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/history',
    name: 'History',
    component: History,
    meta: { requiresAuth: true }
  },
  {
    path: '/room/:roomId',
    name: 'Room',
    component: RoomLobby,
    props: true,
    meta: { requiresAuth: true }
  },
  {
    path: '/game/:roomId',
    name: 'Game',
    component: Game,
    props: true,
    meta: { requiresAuth: true }
  },
  {
    path: '/room-lobby',
    name: 'RoomLobby',
    component: RoomLobby,
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const auth = useAuthStore()
  
  // 检查是否需要认证
  if (to.meta.requiresAuth && !auth.token) {
    // 需要认证但未登录，重定向到登录页
    next({ path: '/', query: { redirect: to.fullPath } })
    return
  }
  
  // 已登录用户访问登录页，重定向到首页
  if (to.path === '/' && auth.token) {
    const redirect = (to.query && to.query.redirect) ? String(to.query.redirect) : '/home'
    next(redirect)
    return
  }
  
  next()
})

export default router
